package reflect;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URISyntaxException;
/**
 * 自动调用与Test5在同一个包中那些被@AutoRunClass标注的类中被@AutoRunMethod
 * 标注的方法指定次.
 * 次数由@AutoRunMethod参数决定
 */
public class Test5 {
    public static void main(String[] args) throws URISyntaxException, ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException {
        File dir = new File(Test5.class.getResource(".").toURI());
        File[] subs = dir.listFiles(f->f.getName().endsWith(".class"));
        for(File file : subs){
            String fileName = file.getName();
            String className = fileName.substring(0,fileName.indexOf("."));
            Class cls = Class.forName(Test5.class.getPackage().getName()+"."+className);
            if (cls.isAnnotationPresent(AutoRunClass.class)){
                Object obj = cls.newInstance();
                Method[] methods = cls.getDeclaredMethods();
                for(Method method : methods){
                    if (method.isAnnotationPresent(AutoRunMethod.class)){
                        AutoRunMethod arm = method.getAnnotation(AutoRunMethod.class);
                        for (int i = 0;i<arm.value();i++){
                            method.invoke(obj);
                        }
                    }
                }
            }
        }
    }
}
